package com.ruoyi.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.AutoCache;
import com.ruoyi.common.annotation.DataUrlPrefix;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.stream.Collectors;

@Aspect
@Component
public class DataUrlPrefixAspect {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${server.urlPrefix}")
    private String urlPrefix;

    private String urlPrefixOld = "http://47.92.210.126:8090";

    @Around("@annotation(com.ruoyi.common.annotation.DataUrlPrefix)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        DataUrlPrefix dataUrlPrefix = getAnnotation(joinPoint, DataUrlPrefix.class);
        logger.info("url前缀为{}",urlPrefix);
        Object result = joinPoint.proceed(joinPoint.getArgs());
        logger.info("响应结果为{}", JSON.toJSONString(result));
        result = replaceUrlPrefix(result,dataUrlPrefix.fields());
        logger.info("需要替换的字段{}", dataUrlPrefix.fields());
        logger.info("替换后结果为{}", JSON.toJSONString(result));
        return result;
    }

    Object replaceUrlPrefix(Object result,String fields) {
        if (result == null || fields == null || fields.isEmpty()) {
            return result;
        }
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(result));
        jsonArray.stream().map(obj->{
            JSONObject jsonObj = (JSONObject)obj;
            for (String field:fields.split(",")) {
                jsonObj.put(field,replaceUrlPrefix(jsonObj.get(field)));
            }
            return obj;
        }).collect(Collectors.toCollection(JSONArray::new));
        return result;
    }

    Object replaceUrlPrefix(Object fieldObject) {
        if (fieldObject == null) {
            return fieldObject;
        }
        String fieldString = fieldObject.toString();
        return fieldString.replaceAll(urlPrefixOld,urlPrefix);
    }

    private <T extends Annotation> T getAnnotation(ProceedingJoinPoint jp, Class<T> clazz) {
        MethodSignature sign = (MethodSignature) jp.getSignature();
        Method method = sign.getMethod();
        return method.getAnnotation(clazz);
    }
}

